package imgshare.shiro;

import cn.hutool.core.bean.BeanUtil;
import imgshare.model.User;
import imgshare.model.vo.UserInfo;
import imgshare.service.UserService;
import imgshare.util.JWTUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.pam.UnsupportedTokenException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.Collections;

@Component
@Lazy
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    @Lazy
    private JWTUtil jwtUtil;
    @Autowired
    @Lazy
    private UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        UserInfo userInfo = (UserInfo)SecurityUtils.getSubject().getPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        authorizationInfo.setRoles(Collections.singleton(userInfo.getRole()));
        authorizationInfo.setStringPermissions(Collections.singleton(userInfo.getPermission()));

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        JWTToken token = (JWTToken) authenticationToken;

        String userId = jwtUtil.getClaimsByToken((String)token.getPrincipal()).getSubject();

        if (userId == null) {
            throw new UnsupportedTokenException("token无效");
        }
        System.out.println("shiroRealm[38]userId:" + userId);

        User user = userService.findOne(Integer.valueOf(userId));
        if (user == null) {
            throw new UnknownAccountException("未知账号，请检查请求参数");
        } else if (user.getLocked()) {
            throw new LockedAccountException("账号已锁定");
        }

        UserInfo userInfo = new UserInfo();
        BeanUtil.copyProperties(user,userInfo);

        //todo 存疑
        return new SimpleAuthenticationInfo(userInfo,token.getCredentials(),getName());
    }
}
